<template>
  <div class="price-ranking">
    <!-- 筛选器区域 -->
    <div class="filters-section">
      <div class="filters-container">
        <div class="filters-grid">
          <!-- 排行榜类型选择 -->
          <div class="filter-item">
            <n-text class="filter-label">排行榜类型</n-text>
            <n-select
              v-model:value="filters.type"
              :options="rankingTypeOptions"
              placeholder="选择排行榜类型"
              size="small"
              @update:value="handleFilterChange"
            />
          </div>

          <!-- 时间范围选择 -->
          <div class="filter-item">
            <n-text class="filter-label">时间范围</n-text>
            <n-select
              v-model:value="filters.timeRange"
              :options="timeRangeOptions"
              placeholder="选择时间范围"
              size="small"
              @update:value="handleFilterChange"
            />
          </div>

          <!-- 物品等级筛选 -->
          <div class="filter-item">
            <n-text class="filter-label">物品等级</n-text>
            <n-select
              v-model:value="filters.grade"
              :options="gradeOptions"
              placeholder="选择等级"
              size="small"
              clearable
              @update:value="handleFilterChange"
            />
          </div>

          <!-- 价格范围 -->
          <div class="filter-item price-range">
            <n-text class="filter-label">价格范围（哈夫币）</n-text>
            <n-space :size="8">
              <n-input-number
                v-model:value="filters.minPrice"
                placeholder="最低价格"
                :min="0"
                size="small"
                style="width: 100px;"
                @update:value="handleFilterChange"
              />
              <n-text :depth="3" style="font-size: 12px;">-</n-text>
              <n-input-number
                v-model:value="filters.maxPrice"
                placeholder="最高价格"
                :min="0"
                size="small"
                style="width: 100px;"
                @update:value="handleFilterChange"
              />
            </n-space>
          </div>

          <!-- 操作按钮 -->
          <div class="filter-actions">
            <n-button size="small" @click="refreshData" :loading="loading">
              <template #icon>
                <n-icon><RefreshOutline /></n-icon>
              </template>
              刷新
            </n-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 排行榜列表 -->
    <div class="ranking-list-section">
      <!-- 加载状态 - 使用骨架屏 -->
      <div v-if="loading" class="skeleton-list">
        <loading-skeleton type="list" :count="pageSize" />
      </div>

      <!-- 实际内容 -->
      <div v-else-if="rankingData.length > 0" class="ranking-items">
          <div
            v-for="(item, index) in rankingData"
            :key="item.object_id"
            class="ranking-item"
            @click="showItemDetail(item.object_id)"
          >
            <!-- 排名徽章 -->
            <div class="rank-section">
              <div class="rank-badge" :class="getRankClass(getRank(index))">
                <span class="rank-number">{{ getRank(index) }}</span>
              </div>
            </div>

            <!-- 物品信息 -->
            <div class="item-info">
              <div class="item-image" :class="`grade-bg-${item.grade}`">
                <n-avatar
                  :size="72"
                  :src="item.image_url"
                  :fallback-src="'/images/item-placeholder.png'"
                  object-fit="cover"
                >
                  <template #fallback>
                    <n-icon :size="36">
                      <CubeOutline />
                    </n-icon>
                  </template>
                </n-avatar>

                <!-- 等级标识 -->
                <div class="grade-badge" :class="`grade-${item.grade}`">
                  {{ item.grade }}
                </div>
              </div>

              <!-- 物品名称和元数据 - 放在图片右侧 -->
              <div class="item-name-meta-overlay">
                <div class="item-name">
                  <n-text strong style="font-size: 15px;">{{ item.name }}</n-text>
                </div>

                <div class="item-meta">
                  <n-space :size="6">
                    <n-tag size="tiny" type="info">{{ translateCategory(item.primary_class) }}</n-tag>
                    <n-tag size="tiny" type="default" v-if="item.second_class">
                      {{ translateCategory(item.second_class) }}
                    </n-tag>
                    <n-text :depth="3" style="font-size: 11px;">
                      {{ item.width }}×{{ item.length }}
                    </n-text>
                  </n-space>
                </div>
              </div>
            </div>

            <!-- 价格信息区域 -->
            <div class="price-section">
              <!-- 当前价格 -->
              <div class="current-price">
                <n-text :depth="3" style="font-size: 12px;">当前价格</n-text>
                <div class="price-value">
                  <n-text strong style="font-size: 18px; color: var(--n-primary-color);">
                    {{ formatPrice(item.current_price) }}
                  </n-text>
                  <n-text :depth="3" style="font-size: 11px;">哈夫币</n-text>
                </div>
              </div>

              <!-- 价格变化 -->
              <div class="price-change" v-if="showPriceChange(item)">
                <n-space align="center" :size="4" style="margin-bottom: 2px;">
                  <n-icon
                    :size="16"
                    :color="getPriceChangeColor(item.price_change)"
                  >
                    <ArrowUpOutline v-if="item.price_change > 0" />
                    <ArrowDownOutline v-else-if="item.price_change < 0" />
                    <RemoveOutline v-else />
                  </n-icon>

                  <n-text
                    :style="{ color: getPriceChangeColor(item.price_change), fontSize: '13px' }"
                    strong
                  >
                    {{ formatPriceChange(item.price_change, item.price_change_percentage) }}
                  </n-text>
                </n-space>

                <n-text :depth="3" style="font-size: 11px;">
                  {{ getPreviousPriceLabel() }}: {{ formatPrice(item.previous_price) }}
                </n-text>
              </div>
            </div>

            <!-- 价格统计信息 -->
            <div class="stats-section">
              <div class="price-stats">
                <div class="stat-item">
                  <n-text :depth="3" style="font-size: 11px;">最高</n-text>
                  <n-text strong style="font-size: 12px; color: #f56c6c;">
                    {{ formatPrice(item.highest_price || 0) }}
                  </n-text>
                </div>

                <div class="stat-item">
                  <n-text :depth="3" style="font-size: 11px;">平均</n-text>
                  <n-text strong style="font-size: 12px; color: #909399;">
                    {{ formatPrice(item.average_price || 0) }}
                  </n-text>
                </div>

                <div class="stat-item">
                  <n-text :depth="3" style="font-size: 11px;">最低</n-text>
                  <n-text strong style="font-size: 12px; color: #67c23a;">
                    {{ formatPrice(item.lowest_price || 0) }}
                  </n-text>
                </div>
              </div>

              <!-- 与平均价格比较 -->
              <div class="comparison" v-if="item.compare_to_average">
                <n-space align="center" :size="4">
                  <n-text :depth="3" style="font-size: 11px;">较平均</n-text>
                  <n-text
                    :style="{
                      color: item.compare_to_average.percentage > 0 ? '#f56c6c' : '#67c23a',
                      fontSize: '11px'
                    }"
                    strong
                  >
                    {{ item.compare_to_average.percentage > 0 ? '+' : '' }}{{ item.compare_to_average.percentage.toFixed(1) }}%
                  </n-text>
                </n-space>
              </div>
            </div>

            <!-- 趋势和操作 -->
            <div class="action-section">
              <div class="trend-indicator">
                <n-tag
                  :type="getTrendType(item.trend)"
                  size="small"
                >
                  {{ getTrendLabel(item.trend) }}
                </n-tag>
              </div>

              <div class="actions">
                <n-button size="tiny" quaternary @click.stop="showItemDetail(item.object_id)">
                  详情
                </n-button>
              </div>
            </div>
          </div>
        </div>

      <!-- 空状态 -->
      <n-empty
        v-else
        description="暂无排行榜数据"
        style="margin: 40px 0;"
      >
        <template #icon>
          <n-icon :size="48" :depth="3">
            <TrophyOutline />
          </n-icon>
        </template>
      </n-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="total > 0">
      <n-space justify="center">
        <n-pagination
          v-model:page="currentPage"
          v-model:page-size="pageSize"
          :item-count="total"
          :page-sizes="[20, 50, 100]"
          show-size-picker
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        />
      </n-space>
    </div>

    <!-- 物品详情弹窗 -->
    <item-detail-modal
      v-model:show="showDetailModal"
      :object-id="selectedItemId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import {
  RefreshOutline,
  TrophyOutline,
  CubeOutline,
  ArrowUpOutline,
  ArrowDownOutline,
  RemoveOutline
} from '@vicons/ionicons5'
import type { RankingType, TimeRange, RankingItem, RankingResponse } from '@/types/ranking'
import { getRankingList, RANKING_TYPES } from '@/api/ranking'
import ItemDetailModal from '@/components/ItemDetailModal.vue'
import LoadingSkeleton from '@/components/common/LoadingSkeleton.vue'

// 响应式数据
const loading = ref(false)
const rankingData = ref<RankingItem[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const showDetailModal = ref(false)
const selectedItemId = ref(0)

// 筛选器
const filters = reactive({
  type: 'highest_price' as RankingType,
  timeRange: 'day' as TimeRange,
  grade: null as number | null,
  minPrice: null as number | null,
  maxPrice: null as number | null
})

// 排行榜类型选项
const rankingTypeOptions = computed(() => {
  return Object.entries(RANKING_TYPES).map(([key, value]) => ({
    label: value.label,
    value: key
  }))
})

// 时间范围选项
const timeRangeOptions = [
  { label: '最近1小时', value: 'hour' },
  { label: '今日', value: 'day' },
  { label: '最近7天', value: 'week' },
  { label: '最近30天', value: 'month' }
]

// 等级选项
const gradeOptions = [
  { label: '1级', value: 1 },
  { label: '2级', value: 2 },
  { label: '3级', value: 3 },
  { label: '4级', value: 4 },
  { label: '5级', value: 5 },
  { label: '6级', value: 6 }
]

// 获取排名
const getRank = (index: number) => {
  return (currentPage.value - 1) * pageSize.value + index + 1
}

// 获取排名样式类
const getRankClass = (rank: number) => {
  if (rank === 1) return 'rank-first'
  if (rank === 2) return 'rank-second'
  if (rank === 3) return 'rank-third'
  if (rank <= 10) return 'rank-top10'
  return 'rank-normal'
}

// 格式化价格
const formatPrice = (price: number) => {
  if (price >= 10000) {
    return (price / 10000).toFixed(1) + '万'
  }
  return price.toLocaleString()
}

// 显示价格变化
const showPriceChange = (item: RankingItem) => {
  return item.previous_price > 0 && item.price_change !== undefined
}

// 格式化价格变化
const formatPriceChange = (change: number, percentage: number) => {
  const sign = change > 0 ? '+' : ''
  const percentageSign = percentage > 0 ? '+' : ''

  if (Math.abs(change) >= 10000) {
    const changeW = (change / 10000).toFixed(1)
    return `${sign}${changeW}万 (${percentageSign}${percentage.toFixed(1)}%)`
  } else if (Math.abs(change) >= 1000) {
    const changeK = (change / 1000).toFixed(1)
    return `${sign}${changeK}k (${percentageSign}${percentage.toFixed(1)}%)`
  }
  return `${sign}${change.toLocaleString()} (${percentageSign}${percentage.toFixed(1)}%)`
}

// 获取价格变化颜色
const getPriceChangeColor = (change: number) => {
  if (change > 0) return '#f56c6c'
  if (change < 0) return '#67c23a'
  return '#909399'
}

// 获取趋势类型
const getTrendType = (trend: string) => {
  switch (trend) {
    case 'up': return 'error'
    case 'down': return 'success'
    default: return 'default'
  }
}

// 获取趋势标签
const getTrendLabel = (trend: string) => {
  switch (trend) {
    case 'up': return '上涨'
    case 'down': return '下跌'
    default: return '平稳'
  }
}

// 获取前期价格标签
const getPreviousPriceLabel = () => {
  switch (filters.timeRange) {
    case 'hour': return '较1小时前'
    case 'day': return '较昨日'
    case 'week': return '较7天前'
    case 'month': return '较30天前'
    default: return '前值'
  }
}

// 分类汉化
const translateCategory = (category: string) => {
  const categoryMap: Record<string, string> = {
    // 主分类
    'props': '道具',
    'weapon': '武器',
    'armor': '防具',
    'accessory': '饰品',
    'material': '材料',
    'consumable': '消耗品',
    'misc': '杂项',
    'equipment': '装备',
    'tool': '工具',

    // 子分类
    'collection': '收藏品',
    'quest': '任务物品',
    'crafting': '制作材料',
    'enhancement': '强化材料',
    'food': '食物',
    'potion': '药水',
    'scroll': '卷轴',
    'gem': '宝石',
    'ore': '矿石',
    'herb': '草药',
    'cloth': '布料',
    'leather': '皮革',
    'metal': '金属',
    'wood': '木材',
    'stone': '石材',
    'crystal': '水晶',
    'card': '卡片',
    'book': '书籍',
    'key': '钥匙',
    'container': '容器',
    'furniture': '家具',
    'decoration': '装饰品'
  }

  return categoryMap[category] || category
}

// 获取排行榜数据
const fetchRankingData = async () => {
  try {
    loading.value = true

    const params = {
      type: filters.type,
      time_range: filters.timeRange,
      page: currentPage.value,
      page_size: pageSize.value,
      grade: filters.grade || undefined,
      min_price: filters.minPrice || undefined,
      max_price: filters.maxPrice || undefined
    }

    const response = await getRankingList(params)

    if (response.code === 1 && response.data) {
      rankingData.value = (response.data as unknown as RankingResponse).list || []
      total.value = (response.data as unknown as RankingResponse).total || 0
    } else {
      console.warn('获取排行榜数据失败:', response.msg || response.message)
      rankingData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取排行榜数据失败:', error)
    rankingData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchRankingData()
}

// 处理筛选器变化
const handleFilterChange = () => {
  currentPage.value = 1
  fetchRankingData()
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchRankingData()
}

// 处理页面大小变化
const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchRankingData()
}

// 显示物品详情
const showItemDetail = (objectId: number) => {
  console.log('PriceRanking: 点击显示物品详情, objectId:', objectId)
  selectedItemId.value = objectId
  showDetailModal.value = true
  console.log('PriceRanking: 设置状态完成, selectedItemId:', selectedItemId.value, 'showDetailModal:', showDetailModal.value)
}

// 监听筛选器变化
watch(() => [filters.type, filters.timeRange], () => {
  handleFilterChange()
}, { deep: true })

// 组件挂载时获取数据 - 优化初始化
onMounted(() => {
  // 立即获取排行榜数据（关键内容）
  fetchRankingData()

})
</script>

<style scoped>
.price-ranking {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.filters-section {
  margin-bottom: 12px;
}

.filters-container {
  background: var(--n-card-color);
  border: 1px solid var(--n-border-color);
  border-radius: 8px;
  padding: 12px 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.filters-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)) auto;
  gap: 12px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.filter-item.price-range {
  grid-column: span 2;
}

.filter-label {
  font-size: 13px;
  font-weight: 500;
  color: var(--n-text-color-2);
  white-space: nowrap;
  flex-shrink: 0;
  min-width: 60px;
}

.filter-actions {
  display: flex;
  align-items: center;
  justify-self: end;
}



.ranking-list-section {
  min-height: 400px;
}

.ranking-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.ranking-item {
  display: grid;
  grid-template-columns: auto 1fr auto auto auto;
  gap: 16px;
  align-items: flex-start;
  padding: 14px;
  background: var(--n-card-color);
  border: 1px solid var(--n-border-color);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.ranking-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: transparent;
  transition: background 0.3s ease;
}

.ranking-item:hover {
  border-color: var(--n-primary-color);
  box-shadow: 0 4px 16px rgba(24, 160, 88, 0.15);
  transform: translateY(-2px);
}

.ranking-item:hover::before {
  background: var(--n-primary-color);
}

/* 排名区域 */
.rank-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  gap: 6px;
  height: 72px;
}

/* 排名徽章 */
.rank-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 42px;
  border-radius: 50%;
  font-weight: bold;
  font-size: 16px;
  position: relative;
  overflow: hidden;
}

.rank-first {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #8b4513;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
}

.rank-second {
  background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
  color: #666;
  box-shadow: 0 2px 8px rgba(192, 192, 192, 0.3);
}

.rank-third {
  background: linear-gradient(135deg, #cd7f32, #daa520);
  color: #fff;
  box-shadow: 0 2px 8px rgba(205, 127, 50, 0.3);
}

.rank-top10 {
  background: var(--n-primary-color-suppl);
  color: var(--n-primary-color);
  border: 1px solid var(--n-primary-color);
}

.rank-normal {
  background: var(--n-card-color);
  color: var(--n-text-color-3);
  border: 1px solid var(--n-border-color);
}

/* 物品信息 */
.item-info {
  position: relative;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
  height: 72px; /* 固定高度为图片高度 */
}

.item-image {
  position: absolute;
  top: 0;
  left: 0;
  flex-shrink: 0;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 0;
  overflow: hidden;
  width: 72px;
  height: 72px;
}

.item-image .n-avatar {
  display: block;
  border-radius: 6px;
  margin: 0 !important;
  padding: 0 !important;
}

.grade-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: bold;
  color: white;
  border: 1px solid white;
}

.grade-1 { background: var(--grade-bg-1); }
.grade-2 { background: var(--grade-bg-2); }
.grade-3 { background: var(--grade-bg-3); }
.grade-4 { background: var(--grade-bg-4); }
.grade-5 { background: var(--grade-bg-5); }
.grade-6 { background: var(--grade-bg-6); }

/* 物品名称和元数据覆盖层 - 位于图片右侧 */
.item-name-meta-overlay {
  position: absolute;
  top: 0;
  left: 84px; /* 图片宽度72px + 12px间距 */
  right: 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
  z-index: 1;
}

.item-name-meta-overlay .item-name {
  margin-bottom: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-name-meta-overlay .item-meta {
  margin-bottom: 0;
}

/* 价格区域 */
.price-section {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  gap: 6px;
  min-width: 140px;
}

.current-price {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.price-value {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.price-change {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

/* 统计区域 */
.stats-section {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  gap: 6px;
  min-width: 120px;
}

.price-stats {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 6px;
}

.comparison {
  padding-top: 4px;
  border-top: 1px solid var(--n-border-color);
}

/* 操作区域 */
.action-section {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  gap: 6px;
  align-items: center;
  min-width: 80px;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

/* 变化信息 */
.change-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 6px;
  min-width: 80px;
}

.pagination-section {
  padding: 20px 0;
  border-top: 1px solid var(--n-border-color);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .filters-container {
    padding: 10px 12px;
  }

  .filters-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }

  .filter-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .filter-item.price-range {
    grid-column: span 1;
  }

  .filter-label {
    min-width: auto;
    font-size: 12px;
  }

  .filter-actions {
    justify-self: stretch;
  }

  .filter-actions .n-button {
    width: 100%;
  }



  .ranking-item {
    grid-template-columns: auto 1fr auto;
    gap: 10px;
    padding: 12px;
  }

  .stats-section,
  .action-section {
    display: none;
  }

  .price-section {
    min-width: 100px;
  }

  .rank-badge {
    width: 36px;
    height: 36px;
    font-size: 14px;
  }

  .item-info {
    height: 56px;
  }

  .item-image {
    width: 56px;
    height: 56px;
  }

  .item-image .n-avatar {
    width: 56px !important;
    height: 56px !important;
  }

  .item-name-meta-overlay {
    left: 68px; /* 移动端图片宽度56px + 12px间距 */
  }

  .current-price .price-value {
    font-size: 16px;
  }
}
</style>
